package com.jt.tenant.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;
import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetBatteryInfo;
import com.jt.tenant.conn.GetEditBatteryBuyTime;
import com.jt.tenant.dialog.MyTimePopup;
import com.jt.tenant.widget.Tools;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by yzf on 2016/2/16.
 */
public class BatteryStateActivity extends JTActivity implements View.OnClickListener,OnChartGestureListener, OnChartValueSelectedListener {

    public static OnChangeCallBack OnChangeCallBack;

    private TextView title_name1;

    private TextView tv_dianya, battery_setting, battery_text, flameoutLastTime;

    private LinearLayout battery_pross,shutdown_time_lin,lin_main_title;

    private String normal_color = "#ff6565", danger_color = "#eb2d2d";

    private ImageView iv_battery_state;

    private LineChart mChart;

    public Date date1;

    private MyTimePopup myTimePopup;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_battery_state);

        tv_dianya = (TextView) findViewById(R.id.tv_dianya);

        iv_battery_state = (ImageView) findViewById(R.id.iv_battery_state);

        (title_name1 = (TextView) findViewById(R.id.tv_title_name)).setText("电瓶状态");

        flameoutLastTime = (TextView) findViewById(R.id.flameoutLastTime);

        (battery_setting = (TextView) findViewById(R.id.battery_setting)).setOnClickListener(this);

        battery_pross = (LinearLayout) findViewById(R.id.battery_pross);

        lin_main_title = (LinearLayout) findViewById(R.id.lin_main_title);

        shutdown_time_lin = (LinearLayout) findViewById(R.id.shutdown_time_lin);

        battery_text = (TextView) findViewById(R.id.battery_text);

        mChart = (LineChart) findViewById(R.id.chart1);

        (OnChangeCallBack = new OnChangeCallBack() {

            private GetBatteryInfo getBatteryInfo = new GetBatteryInfo(new AsyCallBack<GetBatteryInfo.Info>() {

                @Override
                public void onSuccess(String toast, int type, GetBatteryInfo.Info info) throws Exception {

                    if (info.list.size() > 0) {

                        tv_dianya.setText(voltage(info.list.get(info.list.size() - 1).voltageRest));

                        if (Float.parseFloat(info.list.get(info.list.size() - 1).voltageRest) > 11) {

                            iv_battery_state.setVisibility(View.GONE);

                            shutdown_time_lin.setBackgroundColor(Color.parseColor(normal_color));

                            lin_main_title.setBackgroundColor(Color.parseColor(normal_color));

                        } else {

                            iv_battery_state.setVisibility(View.VISIBLE);

                            shutdown_time_lin.setBackgroundColor(Color.parseColor(danger_color));

                            lin_main_title.setBackgroundColor(Color.parseColor(danger_color));

                        }
                    }else {

                        tv_dianya.setText("0");

                        iv_battery_state.setVisibility(View.VISIBLE);

                        shutdown_time_lin.setBackgroundColor(Color.parseColor(danger_color));

                        lin_main_title.setBackgroundColor(Color.parseColor(danger_color));

                    }

                    setData(info);

                    flameoutLastTime.setText("上次熄火：" + info.flameoutLastTime);

                    if(!info.batteryRemain.equals("")) {

                        battery_text.setVisibility(View.VISIBLE);

                        measureBattery(Integer.parseInt(info.batteryRemain));

                        battery_text.setText(info.batteryRemain + "个月");

                    }


                }

            }

            );

            @Override
            public void onChange() {

                getBatteryInfo.execute(context);

            }

        }).onChange();

        showChart();


        myTimePopup = new MyTimePopup(context, null, new Date(), MyTimePopup.Type.YEAR_MONTH_DAY){

            private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            @Override
            public void onSubmit(Date date) {

                new GetEditBatteryBuyTime(simpleDateFormat.format(date1 = date), new AsyCallBack<GetEditBatteryBuyTime.Info>(){

                    @Override
                    public void onSuccess(String toast, int type, GetEditBatteryBuyTime.Info info) throws Exception {

                        UtilToast.show(context, "设置成功");

                        setTime(date1);

                        if(BatteryStateActivity.OnChangeCallBack != null){

                            BatteryStateActivity.OnChangeCallBack.onChange();

                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {

                        UtilToast.show(context, "设置失败");

                    }

                }).execute(context);

            }

        };


    }

    /***
     * 电瓶剩余寿命
     *
     * @param
     */

    private void measureBattery(final int number) {

        new Handler() {

            int left_margin = 55 + (48 - number) * 11;

            @Override
            public void handleMessage(Message msg) {

                if (msg.what < 10) {

                    JTApplication.ScaleScreenHelper.loadViewPadding(battery_pross, left_margin, 10, 0, 0);

                    sendEmptyMessageDelayed(msg.what + 1, 100);

                }

            }

        }.sendEmptyMessageDelayed(0, 100);


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            // 电瓶设置
            case R.id.battery_setting:

                myTimePopup.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                break;

        }

    }

    public interface OnChangeCallBack {

        void onChange();

    }

    private SpannableString voltage(String str) {

        SpannableString s = new SpannableString(str + "V");

        s.setSpan(new RelativeSizeSpan(2.6f), 0, str.length(), 0);

        s.setSpan(new RelativeSizeSpan(1.7f), str.length(), s.length(), 0);

        if (Float.parseFloat(str) > 11) {

            s.setSpan(new ForegroundColorSpan(Color.parseColor(normal_color)), 0, s.length(), 0);

        } else {

            s.setSpan(new ForegroundColorSpan(Color.parseColor(danger_color)), 0, s.length(), 0);

        }

        return s;

    }

    private void showChart(){

        mChart = (LineChart) findViewById(R.id.chart1);
        mChart.setOnChartGestureListener(this);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawGridBackground(false);

        mChart.setDescription("");
        mChart.setNoDataTextDescription("You need to provide data for the chart.");
        mChart.setTouchEnabled(true);
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setPinchZoom(false);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setEnabled(false);

        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        LimitLine ll1 = new LimitLine(14f, "电压偏高");
        ll1.setTextColor(Color.parseColor("#ff6565"));
        ll1.setLineWidth(1f);
        ll1.enableDashedLine(10f, 10f, 0f);
        ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        ll1.setTextSize(10f);
        ll1.setTypeface(tf);

        LimitLine ll2 = new LimitLine(12f, "电压偏低");
        ll2.setTextColor(Color.parseColor("#ff6565"));
        ll2.setLineWidth(1f);
        ll2.enableDashedLine(10f, 10f, 0f);
        ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
        ll2.setTextSize(10f);
        ll2.setTypeface(tf);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        leftAxis.removeAllLimitLines(); // reset all limit lines to avoid overlapping lines
        leftAxis.addLimitLine(ll1);
        leftAxis.addLimitLine(ll2);
        leftAxis.setAxisMaxValue(15f);
        leftAxis.setAxisMinValue(11f);
        //leftAxis.setYOffset(20f);
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        leftAxis.setDrawZeroLine(false);

        // limit lines are drawn behind data (and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);

        mChart.getAxisRight().setEnabled(false);

        mChart.animateX(2500);
        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();
        l.setForm(Legend.LegendForm.LINE);


    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.line, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    set.setDrawValues(!set.isDrawValuesEnabled());
                }

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if(mChart.getData() != null) {
                    mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
                    mChart.invalidate();
                }
                break;
            }
            case R.id.actionToggleFilled: {

                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    if (set.isDrawFilledEnabled())
                        set.setDrawFilled(false);
                    else
                        set.setDrawFilled(false);
                }
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleCircles: {
                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    if (set.isDrawCirclesEnabled())
                        set.setDrawCircles(false);
                    else
                        set.setDrawCircles(true);
                }
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleCubic: {
                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    set.setMode(set.getMode() == LineDataSet.Mode.CUBIC_BEZIER
                            ? LineDataSet.Mode.LINEAR
                            :  LineDataSet.Mode.CUBIC_BEZIER);
                }
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleStepped: {
                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    set.setMode(set.getMode() == LineDataSet.Mode.STEPPED
                            ? LineDataSet.Mode.LINEAR
                            :  LineDataSet.Mode.STEPPED);
                }
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHorizontalCubic: {
                List<ILineDataSet> sets = mChart.getData()
                        .getDataSets();

                for (ILineDataSet iSet : sets) {

                    LineDataSet set = (LineDataSet) iSet;
                    set.setMode(set.getMode() == LineDataSet.Mode.HORIZONTAL_BEZIER
                            ? LineDataSet.Mode.LINEAR
                            :  LineDataSet.Mode.HORIZONTAL_BEZIER);
                }
                mChart.invalidate();
                break;
            }
            case R.id.actionTogglePinch: {
                if (mChart.isPinchZoomEnabled())
                    mChart.setPinchZoom(false);
                else
                    mChart.setPinchZoom(true);

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
                mChart.notifyDataSetChanged();
                break;
            }
            case R.id.animateX: {
                mChart.animateX(3000);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(3000, Easing.EasingOption.EaseInCubic);
                break;
            }
            case R.id.animateXY: {
                mChart.animateXY(3000, 3000);
                break;
            }
            case R.id.actionSave: {
                if (mChart.saveToPath("title" + System.currentTimeMillis(), "")) {
                    Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!",
                            Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT)
                            .show();

                // mChart.saveToGallery("title"+System.currentTimeMillis())
                break;
            }
        }
        return true;
    }



    private void setData(GetBatteryInfo.Info info) {

        ArrayList<Entry> values = new ArrayList<Entry>();

        for (int i = 0; i < info.list.size(); i++) {

            float val;

            if(info.list.get(i).voltageRest == null||info.list.get(i).voltageRest.equals("")|| Tools.F_num(info.list.get(i).voltageRest).equals("0")){

                val = (float) (Math.random()+ 12);

            }else {

                val = Float.parseFloat(Tools.F_num(info.list.get(i).voltageRest));

            }

            values.add(new Entry(i, val));

        }

        LineDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet)mChart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "车辆熄火后电压变化");

            // set the line to be drawn like this "- - - - - -"
//            set1.enableDashedLine(10f, 5f, 0f);
//            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.parseColor("#ff6565"));
            set1.setCircleColor(Color.parseColor("#ff6565"));
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(true);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(false);

            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            }
            else {
                set1.setFillColor(Color.BLACK);
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets

            // create a data object with the datasets
            LineData data = new LineData(dataSets);

            // set data
            mChart.setData(data);
        }
    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gesture", "START, x: " + me.getX() + ", y: " + me.getY());
    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gesture", "END, lastGesture: " + lastPerformedGesture);

        // un-highlight values after the gesture is finished and no single-tap
        if(lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            mChart.highlightValues(null); // or highlightTouch(null) for callback to onNothingSelected(...)
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {
        Log.i("LongPress", "Chart longpressed.");
    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {
        Log.i("DoubleTap", "Chart double-tapped.");
    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {
        Log.i("SingleTap", "Chart single-tapped.");
    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
        Log.i("Fling", "Chart flinged. VeloX: " + velocityX + ", VeloY: " + velocityY);
    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
        Log.i("Scale / Zoom", "ScaleX: " + scaleX + ", ScaleY: " + scaleY);
    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {
        Log.i("Translate / Move", "dX: " + dX + ", dY: " + dY);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOWHIGH", "low: " + mChart.getLowestVisibleX() + ", high: " + mChart.getHighestVisibleX());
        Log.i("MIN MAX", "xmin: " + mChart.getXChartMin() + ", xmax: " + mChart.getXChartMax() + ", ymin: " + mChart.getYChartMin() + ", ymax: " + mChart.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }




}
